package com.zzg.springboot.security.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

import com.zzg.springboot.security.filter.TokenAuthorizationFilter;
import com.zzg.springboot.security.handler.SuccessHandler;
import com.zzg.springboot.security.service.CustomUserDetailsService;

@Configuration // spring-security 配置文件类
@EnableWebSecurity // 启动spring-security 框架
public class SpringSecurityConfig extends WebSecurityConfigurerAdapter {
	@Autowired
	private TokenAuthorizationFilter tokenAuthorizationFilter;

	@Autowired
	private SuccessHandler successHandler;

	@Override
	protected void configure(HttpSecurity http) throws Exception {
		http.addFilterBefore(tokenAuthorizationFilter, UsernamePasswordAuthenticationFilter.class).authorizeRequests().antMatchers("/", "/home", "/code/image").permitAll().anyRequest().authenticated().and()
				.formLogin().loginPage("/login").successHandler(successHandler).permitAll().and().logout().permitAll();
               
	}

	@Override
	protected void configure(AuthenticationManagerBuilder auth) throws Exception {
		auth.userDetailsService(customUserDetailsService());
	}

	/**
	 * 自定义UserDetailsService，从数据库中读取用户信息
	 * 
	 * @return
	 */
	@Bean
	public CustomUserDetailsService customUserDetailsService() {
		return new CustomUserDetailsService();
	}

}
